package com.espirit.eap.manager.workflow;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.espirit.common.WFMessage;
import com.espirit.common.WFMessageService;
import com.espirit.eap.manager.Dictionary;
import com.espirit.eap.manager.DictionaryService;
import com.espirit.eap.manager.EntityStatus;
import com.espirit.eap.manager.EntityStatusManager;
import com.espirit.eap.sa.LoginUserService;
import com.googlecode.cswish.annotation.ParamScope;
import com.googlecode.cswish.annotation.Rest;
import com.googlecode.cswish.model.PageElements;
import com.googlecode.cswish.model.PageInfo;
import com.googlecode.cswish.model.ParameterMap;
import com.googlecode.cswish.model.Reference;
import com.googlecode.cswish.oosearch.QLInfo;
import com.googlecode.cswish.struts.spring.GenericService;
import com.googlecode.cswish.struts.spring.SearchCallback;
import com.opensymphony.xwork2.Result;

@Service
public class FormMessageService {
	@Resource
	WFMessageService  wfMessageService;
	
	@Resource
	GenericService genericService;
	
	@Resource
	LoginUserService loginUserService;
	
	@Resource
	DictionaryService dictionaryService;
	
	@Resource
	EntityStatusManager entityStatusManager;
	
	public PageInfo search(ParameterMap model, int start, int limit,
    		String sort, String dir, boolean newSearch, Reference<QLInfo> qlInfoRef ,
    		@ParamScope(visible=false, value="#ps")PageElements ps ,final String modelName) {
	    if (StringUtils.isEmpty(sort)){
	    	sort = "a.form.createdOn";
	    } else {
	    	if (!sort.startsWith("a.form")){
	    		sort = "a.form." + sort;
	    	}
	    }
	    if (StringUtils.isEmpty(dir)){
	    	dir="desc";
	    }
	    List<String> keys = new ArrayList<String>(model.keySet());
//		for(String key : keys){
//			System.out.println(key);
//			if (!("message.status.text".equals(key) || "message.status.id".equals(key) || "message.statusType".equals(key))){
//				model.setParameter("event." + key, model.get(key));
//				model.remove(key);
//			} 
//		}
		String srcClassName = model.getParameter("message.instance.srcClassName");
		if (!StringUtils.isEmpty(srcClassName)){
			model.setParameter("message.instance.srcClassName", "=" +srcClassName);
		}
	    if (newSearch){
		    ps.setElementLength("execute.message.status.id", 30);
		    
//		    EntityStatus refer = entityStatusManager.getRefer();
//			model.setParameter("form.entityStatus.id", refer.getId());
//			model.setParameter("form.entityStatus.code", refer.getCode());
			
			String statusType = model.getParameter("message.statusType", String.class);
			if (statusType == null){
				model.setParameter("message.statusType", WFMessage.STATUS_OPEN);
				statusType = WFMessage.STATUS_OPEN;
			}
			if (WFMessage.STATUS_OPEN.equals(statusType)){
				model.setParameter("message.hidden", false);
			} else if (WFMessage.STATUS_CLOSE.equals(statusType)){
				model.setParameter("message.hidden", true);
			}
			
			model.setParameter("message.to.id", loginUserService.getLoginUser().getId());
			
//			String modifyTo = "revisionHistory.modifyOn2";
//			model.setRangeParameter(modifyTo, model.getParameter(modifyTo, String.class));
		}
	    
	    PageInfo pageInfo = genericService.search(model, start, limit, sort, dir, newSearch, qlInfoRef ,new SearchCallback() {
			@Override
			public QLInfo afterBuildQL(boolean newSearch, QLInfo qlInfo) {
				if (!newSearch) {
					return qlInfo;
				}
				
				String ql = qlInfo.getQl();
//			    int pos = qlInfo.getQl().indexOf("where");
//			    if (pos > 0){
//			    	ql = qlInfo.getQl().replace("where ", " where a.event.class=" + modelName + "  and ");
//			    } else {
//			    	ql += " where a.event.class=" + modelName ;
//			    }
				qlInfo.setQl(ql);
				return qlInfo;
			}
		}, true, true);
	    
	    return pageInfo;

	}
	
	public Result _approve(List<FormMessage> results){
		if (results == null || results.isEmpty()) return null;
		List forms = new ArrayList();
		for(FormMessage fm : results){
			if (fm != null && fm.getId() != null){
				FormMessage formMessage = genericService.load(FormMessage.class, fm.getId());
				forms.add(formMessage.getForm());
			}
		}
		return wfMessageService._approve(forms);
	}
	
	@Rest(type="_approve")
	public Result _update(FormMessage model){
		if (model == null || model.getId() == null) return null;
		FormMessage formMessage = genericService.load(FormMessage.class, model.getId());
		return wfMessageService._update(formMessage.getMessage());
	}
	
	public List<Map<String,String>> getSrcClassNames(){
		
		List<Dictionary> results = dictionaryService.getDictionariesByType(FormMessage.SRC_CLASSNAME);
		if (results == null) return null;
		
		List<Map<String,String>> srcClassNames  = new ArrayList();
		for(Dictionary dict : results){
			Map<String, String > values = new HashMap<String, String>();
			values.put("id", dict.getValue());
			values.put("name", dict.getName());
			srcClassNames.add(values);
		}
		return srcClassNames;
		
//		List<Map<String,String>> leaveTypes  = new ArrayList();
//		Map<String, String > values = new HashMap<String, String>();
//		values.put("id", "com.hr.LeaveAppItem");
//		values.put("name", "请假单");
//		leaveTypes.add(values);
//		
//		values = new HashMap<String, String>();
//		values.put("id", "com.hr.OtItem");
//		values.put("name", "加班单");
//		leaveTypes.add(values);
//		return leaveTypes;
	}
}
